import 'package:flutter/material.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';

/// Description: 虚线
///
/// @author tangzhentao 
/// @date 2020/7/17 

class DottedLine extends StatelessWidget {
  /// 虚线方向
  final Axis axis;
  /// 水平虚线时 length为Size.Width
  /// 竖直虚线时 length为Size.Height
  final double length;
  /// strokeWidth线宽
  final double? strokeWidth;
  /// 虚线最小长度
  final double gap;
  /// 虚线间隔
  final double interval;
  /// 虚线颜色
  final Color lineColor;

  const DottedLine({
    super.key,
    this.axis = Axis.horizontal,
    this.length = double.infinity,
    this.strokeWidth,
    this.gap = 6.0,
    this.interval = 3.0,
    this.lineColor = XfgColor.colorB8,
  });

  @override
  Widget build(BuildContext context) {
    final Size size;
    if (axis == Axis.vertical) {
      size = Size(strokeWidth?? XfgSize().size0_5, length);
    } else {
      size = Size(length, strokeWidth?? XfgSize().size0_5);
    }

    return CustomPaint(
      size: size,
      painter: DottedLinePainter(
        axis: axis,
        gap: gap,
        interval: interval,
        lineColor: lineColor,
      ),
    );
  }

}

class DottedLinePainter extends CustomPainter {
  Axis axis;
  double gap;
  double interval;
  Color lineColor;

  DottedLinePainter({
    this.axis = Axis.vertical,
    this.gap = 6.0,
    this.interval = 2.0,
    this.lineColor = Colors.black,
  });

  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()
        ..strokeWidth = axis == Axis.horizontal ? size.height : size.width
        ..color = lineColor
        ..isAntiAlias = true
        ..style = PaintingStyle.stroke;

    if (axis == Axis.vertical) {
      double unit = gap + interval;
      int total = size.height ~/ unit;
      double remainder = size.height % unit;
      for (int i = 0; i < total; i++) {
        canvas.drawLine(Offset(size.width / 2, i * unit), Offset(size.width / 2, i * unit + gap), paint);
      }

      if (remainder != 0) {
        canvas.drawLine(Offset(size.width / 2, total * unit), Offset(size.width / 2, size.height), paint);
      }
    } else {
      double unit = gap + interval;
      int total = size.width ~/ unit;
      double remainder = size.width % unit;
      for (int i = 0; i < total; i++) {
        canvas.drawLine(Offset(i * unit, size.height / 2), Offset(i * unit + gap, size.height / 2), paint);
      }

      if (remainder != 0) {
        canvas.drawLine(Offset(total * unit, size.height / 2), Offset(size.width, size.height / 2), paint);
      }
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => this != oldDelegate;
}
